<?php

namespace app\admin\controller;

use app\admin\builder\Form;
use app\admin\builder\Table;

/**
 * 插件管理
 * Class Addon
 * @package app\admin\controller
 */
class Addon extends Admin
{

    protected $addonPath = null;

    public function initialize()
    {
        $this->addonPath = '../addon';
        parent::initialize();
    }


    public function _leftSlide()
    {
        $slide = [
            [
                'title' => '插件列表',
                'child' => [
                    ['menu' => 'admin/addon/addons', 'title' => '插件列表', 'slide_name' => 'addons'],
                ]
            ],
            /*            [
                            'title' => '插件配置',
                            'child' => [
                                ['menu' => 'admin/addon/config', 'title' => '插件配置', 'slide_name' => 'config'],
                            ]
                        ],*/
        ];

        return $slide;
    }


    public function addons()
    {
        $table = new Table();
        if (Request()->isPost()) {


        } else {
            $r = 30;

            $list = scandir($this->addonPath);
            $data = [];

            $addlist = db('addon')->column('name,title,status', 'name');
            foreach ($list as $datum) {
                if ($datum != '.' && $datum != '..') {
                    $config = require_once($this->addonPath . '/' . $datum . '/config.php');
                    $config['status'] = '未安装   <a href="javascript:" class="layui-btn layui-btn-xs layui-btn-normal"
                       data-url="' . url('installaddon') . '" data-role="ajax-post">安装</a>';
                    if (isset($addlist[$config['name']]) && $addlist[$config['name']]['status'] == 1) {
                        $config['status'] = '已安装 <a href="javascript:" class="layui-btn layui-btn-xs layui-btn-warm"
                       data-url="' . url('uninstalladdon') . '" data-role="ajax-post">卸载</a>';
                    }
                    $config['id'] = $config['name'];
                    $data[] = $config;
                }
            }
            // dump($data);

            $this->_setSlide('addons');
            return $table->setTitle('插件列表')
                ->dataSource(['data' => $data], 'user')
                ->button('获取选中项', ['data-role' => 'get_checked'])
                // ->field('id', 'ID')
                ->field('name', '名称')
                ->field('title', '标题')
                ->field('description', '描述')
                ->field('author', '作者')
                ->field('version', '版本')
                ->fieldHtml('status', '状态')
                //->action('安装', ['url' => url('installaddon'), 'class' => 'layui-btn-primary'])
                ->action('配置', ['url' => url('setconfig'), 'class' => 'layui-btn-primary'])
                // ->action('删除', ['url' => url('delete'), 'class' => 'layui-btn-danger'])
                ->show();
        }

    }


    public function setConfig()
    {
        $form = new Form();
        $addonName = input('id', '', 'text');
        if (Request()->isPost()) {
            $input = input();
            $time = time();
            foreach ($input as &$v) {
                $v = text($v); //防止注入
            }
            unset($v);
            $input['update_time'] = $time;
            $addon = db('addon')->where('name', $addonName)->find();
            if ($addon && $addon['status'] == 1) {
                db('addon')->where('name', $addonName)->update(['config' => json_encode($input, JSON_UNESCAPED_UNICODE)]);
                $this->success('修改成功');
            }
            $this->error('修改失败，请确保插件已经安装');

        } else {


            $this->setBreadcrumb([
                ['href' => url('addon/addons'), 'title' => '插件列表'],
            ]);


            $info = require_once($this->addonPath . '/' . parse_name($addonName, 1) . '/config.php');
            $list = $info['config'];
            $config = db('addon')->where('name', $addonName)->value('config');
            $config = json_decode($config, true);
            $data = [
                'id' => $addonName
            ];
            //$data =[];
            $this->_setSlide('form');
            $form->setTitle($info['title'])
                ->form(url('setconfig'))->typeText('id', '插件标识', ['attr' => 'readonly']);
            foreach ($list as $v) {
                $data[$v['name']] = isset($config[$v['name']]) ? $config[$v['name']] : $v['default'];
                $func = 'type' . $v['type'];
                if (method_exists($form, $func)) {
                    $form->$func($v['name'], $v['title'], $v['extra']);
                }
            }
            return $form->setData($data)->show();
        }
    }

    public function uninstallAddon()
    {
        $addonName = input('id', '', 'text');
        $name1 = parse_name($addonName, 1);
        $time = time();
        $addon = db('addon')->where('name', $addonName)->find();
        if (empty($addon)) {
            $this->error('卸载失败，未找到插件');
        }
        $data = [
            'status' => 0,
            'update_time' => $time,
        ];
        db('addon')->where('name', $addonName)->update($data);
        $class_name = "\addon\\$name1\controller\Index";
        if (class_exists($class_name) && method_exists(controller($class_name), 'uninstall')) {
            $rs = controller($class_name)->uninstall();
        }


        cache('all_hooks', null);
        $this->success('卸载成功');
    }

    public function installAddon()
    {
        $addonName = input('id', '', 'text');
        $name1 = parse_name($addonName, 1);
        $info = require_once($this->addonPath . '/' . $name1 . '/config.php');

        $time = time();
        $addon = db('addon')->where('name', $addonName)->find();

        $data = [
            'name' => $info['name'],
            'title' => $info['title'],
            'description' => $info['description'],
            'author' => $info['author'],
            'version' => $info['version'],
            'hooks' => json_encode($info['hooks']),
            'config' => '',
            'status' => 1,
            'update_time' => $time,
        ];

        if ($addon) {

            db('addon')->where('name', $addonName)->update($data);
        } else {
            $data['create_time'] = $time;
            db('addon')->insert($data);
        }
        $class_name = "\addon\\$name1\controller\Index";
        if (class_exists($class_name) && method_exists(controller($class_name), 'install')) {
            $rs = controller($class_name)->install();
        }

        cache('all_hooks', null);
        $this->success('安装成功');
    }


}
